import React from 'react'
import borrowService from 'containers/loan-billing/borrow-and-return.service'
import 'styles/loan-billing/loan-detail.scss'
import ApproveHistory from 'components/template/approve-history'
import ApproveTag from 'components/template/approve-tag'
import { Tabs, Spin, message, Row, Button, Table, Badge, Icon, Modal, Col, Tag, Popover } from 'antd';
import constants from "share/constants";
import moment from "moment/moment";
import repaymentIMG from "images/loan-billing/repayment.png";
import LoanRelatedApplication from 'containers/request/loan-request/loan-related-application';
import customField from "share/customField";
import { messages, queryCurrencyPrecision, getQueryUrlParam } from "share/common";
import SlideFrame from 'components/slide-frame';
import editLoan from "containers/loan-billing/template/edit-loan";
import HonestView from 'components/template/honest-view'
import addLoan from "containers/loan-billing/template/add-loan";
import refundContent from "containers/loan-billing/template/refund-content";
import viewLine from "containers/loan-billing/template/view-line";
import ApprovingEdit from 'containers/approve/approving-edit'
import BottomButton from "containers/loan-billing/template/bottom-button";
import menuRoute from "routes/menuRoute";
import baseService from "share/base.service";
import DebtModal from 'containers/loan-billing/template/debt-modal';
import extendLoad from 'containers/loan-billing/template/extend-load';
import turnPermanent from 'containers/loan-billing/template/turn-permanent';
import ExpenseDetailStep from 'containers/expense-report/components/expense-detail-step';
const TabPane = Tabs.TabPane;

class LoanDetail extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      info: {},
      loading: false,
      status: 'loanInfo',
      subStatus: 'detail',
      repayColumns: [
        {title: messages('common.date')/*日期*/, dataIndex: 'createDate', width: 120, render: value => moment(value).format('YYYY-MM-DD')},
        {title: messages('loan-billing.key1')/*还款单号*/, dataIndex: 'businessCode'},
        {title: messages('loan-billing.key2')/*借款行号*/, dataIndex: 'loanLineNumber'},
        {title: messages('loan-billing.key3')/*还款方式*/, dataIndex: 'type', render: value => value === '0' ? messages('loan-billing.key4')/*现金还款*/ :
            (value === '1' ? messages('loan-billing.key5')/*转账还款*/ : (value === '3' ? messages('loan-billing.key94')/*信用还款*/ : messages('loan-billing.key6')/*报销单还款*/))},
        {title: messages('common.currency')/*币种*/, dataIndex: 'curreny', width: 48},
        {title: messages('loan-billing.key7')/*还款金额*/, dataIndex: 'actRepayAmount', align:'right', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.curreny))},
        {title: messages('common.column.status')/*状态*/, dataIndex: 'status', render: value => value === '1001' ? <Badge text={messages('loan-billing.key8')/*还款中*/} status="processing"/> :
            (value === '1002' ? <Badge text={messages('loan-billing.key9')/*已还款*/} status="success"/> : <Badge text={messages('loan-billing.key10')/*被驳回*/} status="error"/>)}
      ],
      expand: true,
      editShow: false,
      loanTableData: [],
      formInfo: {},
      loanColumns: [
        {title: messages('common.sequence')/*序号*/, dataIndex: 'sequence', width: 108, align: 'center'},
        {title: messages('loan-billing.key12')/*借款类型*/, dataIndex: 'loanTypeName', width: '15%', render: (value,record) => <Popover trigger="hover" content={value}>{value}</Popover>},
        {title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 88},
        {title: messages('loan-billing.key11')/*借款金额*/, dataIndex: 'amount', width: '10%', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('loan-billing.key13')/*收款对象*/, dataIndex: 'payeeName', width: '10%', render: (value,record) => {
            let isEmployee = record.payeeType === 1002;
            return (
              <div style={{textAlign:'right',margin:'0px 10px'}}>
                <div className={isEmployee ? 'table-blue' : 'table-grey'}>{isEmployee ? messages('loan-billing.key14')/*员工*/ : messages('loan-billing.key15')/*供应商*/}</div>
                <img src={repaymentIMG} onClick={(e) => this.handleImgClick(e, record)} style={{ width:'18px', height:'18px', display:'inline-block', float: 'left', marginTop: '2px' }}/>
                {value}
              </div>
            )
          }},
        // https://pmo.mcd.com.cn/jira/browse/TES-2124 收款账户、借款属性第二行隐藏
        // {title: messages('loan-billing.key16')/*收款账户*/, dataIndex: 'payeeAccountName', render: (value, record) => {
        //     return (
        //       <div>
        //         <div>{messages('loan-billing.key17')/*户名*/}:{value}</div>
        //         <div>{messages('loan-billing.key18')/*账户*/}:{record.payeeAccountNumber}</div>
        //       </div>
        //     )
        //   }},
        {title: messages('loan-billing.key19')/*借款属性*/, dataIndex: 'planedRepaymentDate', render: (value, record) => {
            let res = '';
            this.state.loanEnum.map(item => {
              item.value === record.paymentType && (res = item.messageKey);
            });
            return (
              <div>
                <div>{messages('loan-billing.key23')/*计划还款日期*/}:{value ? moment(value).format('YYYY-MM-DD') : '-'}</div>
                {/* <div>付款方式类型:{res}</div> */}
              </div>
            )
          }},
        {title: messages('common.loan.reason')/*借款原因*/, dataIndex: 'remark', render: value => value ? value : '-'}
      ],
      addShow: false,
      title: '',
      recordInfo: '',
      isRepaying: false,
      rowLoading: false,
      refundFrame: false,
      refundParams: {},
      authorityWithRepay: false,
      authorityWithLine: false,
      expenseDetail: menuRoute.getRouteItem('expense-report-detail'),
      adminApprove: props.location.pathname.indexOf('admin-approve-loan-detail') > -1,
      honestModalShow: false,
      honestInfo: {},
      isFinance: false,
      applicationOID: '',
      requestInfo: {},
      loanEnum: [],
      viewFrame: false,
      viewId: '',
      debtInfo: {},
      debtVisible: false,
      loadRestaurantColumns: [
        {title: messages('common.sequence')/*序号*/, dataIndex: 'sequence', width: 108, align: 'center'},
        {title: messages('loan-billing.key12')/*借款类型*/, dataIndex: 'loanTypeName', width: '15%', render: (value,record) => <Popover trigger="hover" content={value}>{value}</Popover>},
        {title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 88},
        {title: messages('loan-billing.key11')/*借款金额*/, dataIndex: 'amount', width: '10%', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('loan-billing.key13')/*收款对象*/, dataIndex: 'payeeName', width: '10%', render: (value,record) => {
            let isEmployee = record.payeeType === 1002;
            return (
              <div style={{textAlign:'right',margin:'0px 10px'}}>
                <div className={isEmployee ? 'table-blue' : 'table-grey'}>{isEmployee ? messages('loan-billing.key14')/*员工*/ : messages('loan-billing.key15')/*供应商*/}</div>
                <img src={repaymentIMG} onClick={(e) => this.handleImgClick(e, record)} style={{ width:'18px', height:'18px', display:'inline-block', float: 'left', marginTop: '2px' }}/>
                {value}
              </div>
            )
          }},
        // https://pmo.mcd.com.cn/jira/browse/TES-2124 收款账户、借款属性第二行隐藏
        // {title: messages('loan-billing.key16')/*收款账户*/, dataIndex: 'payeeAccountName', render: (value, record) => {
        //     return (
        //       <div>
        //         <div>{messages('loan-billing.key17')/*户名*/}:{value}</div>
        //         <div>{messages('loan-billing.key18')/*账户*/}:{record.payeeAccountNumber}</div>
        //       </div>
        //     )
        //   }},
        {title: messages('loan-billing.key19')/*借款属性*/, dataIndex: 'planedRepaymentDate', render: (value, record) => {
            let res = '';
            this.state.loanEnum.map(item => {
              item.value === record.paymentType && (res = item.messageKey);
            });
            return (
              <div>
                <div>{messages('loan-billing.key23')/*计划还款日期*/}:{value ? moment(value).format('YYYY-MM-DD') : '-'}</div>
                {/* <div>付款方式类型:{res}</div> */}
              </div>
            )
          }},
        {title: messages('common.loan.reason')/*借款原因*/, dataIndex: 'remark', render: value => value ? value : '-'},
        {title: messages('loan-billing.key198')/*延长还款日期*/, dataIndex: 'delayDate', render: value => value ? moment(value).format('YYYY-MM-DD') : '-'},
        {title: messages('loan-billing.key199')/*转永久金额*/, dataIndex: 'toForeverAmount', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))}
      ],
      extendMoneyFrame: false,
      turnPermanentFrame: false,
      extendMoneyMode: 'read',
      turnPermanentMode: 'read',
    }
  }

  componentDidMount() {
    this.getInfo(true);
  }

  handleImgClick = (e, record) => {
    e.stopPropagation();
    e.preventDefault();
    this.setState({
      debtVisible: true,
      debtInfo: record
    })
  };

  getInfo = (isFirst) => {
    this.setState({
      loading: true,
      authorityWithRepay: this.props.location.pathname.indexOf('borrow-management') > -1 || this.props.location.pathname.indexOf('loan-and-refund') > -1,
      authorityWithLine: this.props.location.pathname.indexOf('my-borrow') > -1 || this.props.location.pathname.indexOf('borrow-management') > -1 || this.props.location.pathname.indexOf('request') > -1,
      isFinance: this.props.location.pathname.indexOf('financial-management') > -1
    });
    const { loanBillOID, formOID, applicationOID } = this.props.params;
    Promise.all([
      borrowService.getDetailInfo(loanBillOID),
      borrowService.getCustomForm(formOID),
      borrowService.getLoanEnum()
    ]).then(res => {
      this.resDataHandle(res[1].data.customFormFields);
      console.log('res[0].data', res)
      this.setState({
        info: res[0].data,
        applicationOID: applicationOID !== ':applicationOID' ? applicationOID : '',
        formInfo: res[1].data,
        loanEnum: res[2].data
      },() => {
        const { info, loanColumns, authorityWithLine, isFinance, applicationOID, loadRestaurantColumns } = this.state;
        isFirst && info.status === 1001 && info.type === 2006 && authorityWithLine && ((applicationOID && info.directCreate) || (!applicationOID && !info.directCreate)) && loanColumns.push({title: messages('common.operation')/*操作*/, dataIndex: 'operate', render:(value,record) => <div>
            <a onClick={e => this.editRecord(e,record)}>{messages('common.edit')/*编辑*/}</a><span className="ant-divider"/><a onClick={e => this.deleteRecord(e,record)}>{messages('common.delete')/*删除*/}</a>
          </div>});
        isFirst && info.status === 1001 && info.type === 2006 && authorityWithLine && ((applicationOID && info.directCreate) || (!applicationOID && !info.directCreate)) && loadRestaurantColumns.push({title: messages('common.operation')/*操作*/, dataIndex: 'operate', render:(value,record) => <div>
          <a onClick={e => this.editRecord(e,record)}>{messages('common.edit')/*编辑*/}</a><span className="ant-divider"/><a onClick={e => this.deleteRecord(e,record)}>{messages('common.delete')/*删除*/}</a>
        </div>});
        Promise.all([
          borrowService.getLoanTable(info.id,isFinance),
          baseService.getHonestInfo(info.applicant.userOID, info.jobId),
          applicationOID && borrowService.getRequestDetail(applicationOID)
        ]).then(res => {
          let repayStatus = [ 1005, 1006, 1007 ];
          let dataList = res[0].data;
          let isRepaying = false;
          dataList.map(item => {
            ~repayStatus.indexOf(item.status) && (isRepaying = true);
          });
          this.setState({
            isRepaying,
            loanTableData: res[0].data,
            loading: false,
            loanColumns,
            honestInfo: res[1].data,
            requestInfo: res[2] ? res[2].data : {}
          })
        }).catch(() => {
          message.error(messages('loan-billing.key25')/*系统异常*/);
          this.setState({loading: false})
        });
      });
    }).catch(() => {
      message.error(messages('loan-billing.key25')/*系统异常*/);
      this.setState({loading: false})
    })
  };

  //表单信息处理
  resDataHandle = (fields) => {
    fields.map(item => {
      if (item.messageKey === 'applicant') {
        item.isReadOnly = true;
      }
    });
    fields.sort((a, b) => a.sequence > b.sequence || -1);
  };

  //tab切换
  onChangeTabs = (value) => {
    this.setState({status: value});
  };

  //子tab切换
  handleSubTabsChange = (value) => {
    this.setState({subStatus: value});
  };

  //渲染借款单头部信息
  renderHeadInfo = (applicant) => {
    const { info, loading, isRepaying, authorityWithRepay, honestInfo } = this.state;
    return (
      <Spin spinning={loading}>
        <div className="top-info">
          {info.status && info.formCode !== 'JK005' && <ExpenseDetailStep
            info={info}
            type="loan"
            approvalChains={info.approvalChains}
          />}
          <Row className="row-container">
            <span className="top-info-name">{applicant.fullName}</span>
            {
              honestInfo.creditStatus !== 1001 && Number(info.status) < 1005 &&
              <a onClick={this.handleIntoHonest} style={{marginRight:'5px'}}> {messages('expense-parent-report.key106')/*信用分*/}：{honestInfo.score}
                {
                  honestInfo.rankFlag && (
                    <span>
                      <span className="ant-divider default-color-bg"/> {messages('expense-parent-report.key107')/*信用等级*/}：{honestInfo.creditRank}
                    </span>
                  )
                }
              </a>
            }
            <span className="detail-info"> {messages('common.user.id')/*工号*/}:{applicant.employeeID}
              <span className="ant-divider"/> {messages('common.department')/*部门*/}:{applicant.departmentName || '-'}
              <span className="ant-divider"/> {messages('common.user.company')/*员工公司*/}:{applicant.companyName || '-'}
              <span className="ant-divider"/> {messages('common.currency')/*币种*/}:{info.currencyCode}
            </span>
          </Row>
          <Row className="row-container">
            <span className="detail-info detail-info-first">{info.formName}:{info.businessCode}</span>
            {
              !(info.type === 2006 && info.status === 1001) && (
                <span className="detail-info"> {messages('common.submit.date')/*提交日期*/}:{moment(info.submittedDate).format('YYYY-MM-DD')}
                  {info.submittedBy && applicant.userOID !== info.submittedBy && messages('loan-billing.key27',{arg1:info.submittedName})/*,由{arg1}代提*/}
                </span>
              )
            }
            <span className="detail-info"> {messages('loan-billing.key28')/*当前状态*/}:
              {(info.closed || (info.applicationParticipant && info.applicationParticipant.closed === 1)) ? messages('loan-billing.key29')/*已停用*/ : (
                  constants.getTextByValue(String(info.status + '' + info.type), 'documentLoanStatus') ||
                  constants.getTextByValue(String(info.status + '' + info.rejectType), 'documentLoanStatus') ||
                  constants.getTextByValue(String(info.status), 'documentLoanStatus')
                )
              }
            </span>
            {this.isShowHangUp() && (
              <Tag style={{marginLeft: 8}} color="#505564">{messages('loan-billing.key105')/*暂挂*/}</Tag>
            )}
          </Row>
          <LoanRelatedApplication info={info}/>
          <Row className="row-container">
            <span className="amount"> {messages('loan-billing.key11')/*借款金额*/}:{info.currencyCode} {this.filterMoney(info.currencyAmount,queryCurrencyPrecision(info.currencyCode))}
            </span>
            {isRepaying && authorityWithRepay && (
              <span>
                {
                  info.hasWriteOffAmount === info.currencyAmount ? (
                    <span className="detail-info">
                      <Icon type='check-circle-o' style={{color: '#00A854',fontSize:'15px'}}/> {messages('loan-billing.key30')/*已全额还款*/}
                    </span>
                  ) : (
                    <span>
                      <span className="detail-info">{messages('loan-billing.key9')/*已还款*/}:{this.filterMoney(info.hasWriteOffAmount,queryCurrencyPrecision(info.currencyCode))}</span><span className="ant-divider"/>
                      <span className="detail-info" style={{color: '#00A854'}}>{messages('loan-billing.key8')/*还款中*/}:{this.filterMoney(info.lockedWriteOffAmount,queryCurrencyPrecision(info.currencyCode))}</span><span className="ant-divider"/>
                      <span className="detail-info" className='default-color-font'> {messages('loan-billing.key31')/*待还款*/}:{this.filterMoney(info.stayWriteOffAmount,queryCurrencyPrecision(info.currencyCode))}</span>
                    </span>
                  )
                }
              </span>
            )}
          </Row>
        </div>
      </Spin>
    )
  };

  //渲染借款单详情信息
  renderDetailInfo = (applicant) => {
    const { info, loading, expand, loanColumns, loanTableData, applicationOID, formInfo, loadRestaurantColumns } = this.state;
    let customFormValues = info.customFormValues || [];
    customFormValues.sort((a, b) => a.sequence > b.sequence || -1);
    let signName = customField.getSignNameForSubmitter(formInfo && formInfo.customFormPropertyMap);
    let rows = customField.renderFields(customFormValues, info, applicant, '', signName);
    let approvalOID = getQueryUrlParam('approverOID');
    let tab = this.props.params.tab === 'prending_audit' && this.checkFunctionProfiles('finance.audit.edit.enable', [true]);
    return (
      <Spin spinning={loading}>
        <div className="tab-container">
          <h3 className="sub-header-title"> {messages('loan-billing.key33')/*借款单详情*/}
            {
              info.type === 2006 && info.status === 1001 && ((applicationOID && info.directCreate) || (!applicationOID && !info.directCreate)) &&(
                <a className="edit" onClick={() => this.setState({editShow: true})}>{messages('common.edit')/*编辑*/}</a>
              )
            }
            {(approvalOID || tab) && (
              <ApprovingEdit approvalOID={approvalOID}
                             entityOID={info.loanBillOID}
                             formOID={info.formOID}
                             entityType={3001}
                             custFormValues={customFormValues}
                             handleAfterSave={this.getInfo}/>
            )}
            <a className="toggle-button" onClick={this.toggle}>
              {expand ? messages('common.fold') : messages('common.more')}
              <Icon type={expand ? 'up' : 'down'}/>
            </a>
          </h3>
          {rows.map((item) => {
            let isDisplay = expand ? 'block' : 'none';
            return (
              <div style={{display:isDisplay, height: 'auto'}}>
                {item}
              </div>
            )
          })}
        </div>
        <div className="tab-container">
          <h3 className="sub-header-title">{messages('loan-billing.key34')/*借款信息*/}</h3>
          {
            info.status === 1001 && info.type === 2006 && ((applicationOID && info.directCreate) || (!applicationOID && !info.directCreate)) && (
              <Button type='primary' style={{marginBottom: '20px'}} onClick={() => {
                if (formInfo.formCode === 'JK004' || formInfo.formCode === 'JK007' || formInfo.formCode === 'JK006' || formInfo.formCode === 'JK003' || formInfo.formCode === 'JK002') {
                  console.log('formInfo', info)
                  borrowService.handleIsAddLoanLine(info.id).then(res => {
                    if (res.status === 200) {
                      if (res.data) {
                        this.setState({recordInfo: '', title: messages('loan-billing.key35')/*新建借款计划*/}, () => {
                          this.setState({addShow: true})
                        })
                      } else {
                        if (formInfo.formCode === 'JK004') {
                          message.warning('临时找赎备用金，每次只允许申请一笔，如需修改金额，请点击编辑并修改金额');
                        } else {
                          message.warning('已有借款行，无法新建借款行');
                        }
                      }
                    }
                  }).catch(err => {
                    message.error(err)
                  })
                } else {
                  this.setState({recordInfo: '', title: messages('loan-billing.key35')/*新建借款计划*/}, () => {
                    this.setState({addShow: true})
                  })
                }
              }}>{messages('loan-billing.key36')/*新建借款信息*/}</Button>
            )
          }
          <Table columns={formInfo.formCode === 'JK004' ? loadRestaurantColumns :loanColumns}
                 bordered
                 rowKey="id"
                 onRow={record => ({onClick: () => this.handleRowClick(record)})}
                //  expandedRowRender={this.renderContent}
                //  onExpand={this.renderAllExpandedRow}
                 size="middle"
                 dataSource={loanTableData}/>
        </div>
      </Spin>
    )
  };

  handleRowClick = record => {
    console.log('record', record)
    const { info } = this.state
    if(this.props.location.pathname.indexOf('approve-loan') || this.props.location.pathname.indexOf('finance-audit')){
      if (info.formCode === 'JK007') {
        this.setState({ extendMoneyFrame: true, viewId: record.id, extendMoneyMode: 'read' })
      } else if (info.formCode === 'JK006') {
        this.setState({ turnPermanentFrame: true, viewId: record.id, turnPermanentMode: 'read' })
      } else {
        this.setState({viewFrame: true, viewId: record.id});
      }
    }
  };

  renderContent = record => {
    const { rowLoading } = this.state;
    let rowInfo = record._info;
    return rowInfo ? (
      <div>
        <Row>
          <Col span={2}>{messages('loan-billing.key85')/*金额属性*/}</Col>
          <Col span={22}>
            <span>{messages('loan-billing.key56')/*本币金额*/}:{rowInfo.baseCurrencyCode} {rowInfo.baseAmount ? this.filterMoney(rowInfo.baseAmount,queryCurrencyPrecision(rowInfo.baseCurrencyCode),true) : '-'}</span>
            <span style={{marginLeft:'10px'}}>{messages('common.currency.rate')/*汇率*/}:{rowInfo.currencyRate ? rowInfo.currencyRate : '-'}</span>
            <span style={{marginLeft:'10px'}}>{messages('loan-billing.key86')/*汇率日期*/}:{rowInfo.currencyRateApplyDate ? moment(rowInfo.currencyRateApplyDate).format('YYYY-MM-DD') : '-'}</span>
          </Col>
        </Row>
        <Row>
          <Col span={2}>{messages('loan-billing.key71')/*关联申请单*/}</Col>
          <Col span={22}>
            <span>{messages('loan-billing.key87')/*申请单编号*/}:{rowInfo.refApplicationBusinessCode ? rowInfo.refApplicationBusinessCode: '-'}</span>
            <span style={{marginLeft:'10px'}}>{messages('loan-billing.key88')/*申请单金额*/}:{rowInfo.refApplicationCurrencyCode ? rowInfo.refApplicationCurrencyCode: '-'}&nbsp;&nbsp;{rowInfo.refApplicationAmount ? this.filterMoney(rowInfo.refApplicationAmount,queryCurrencyPrecision(rowInfo.refApplicationCurrencyCode),true) : '-'}</span>
          </Col>
        </Row>
        {
          rowInfo.contractAssociatedDTO && Object.keys(rowInfo.contractAssociatedDTO).length > 0 && (
            <Row>
              <Col span={2}>{messages('loan-billing.key106')/*关联合同*/}:</Col>
              <Col span={22}>
                <span>{messages('loan-billing.key107')/*合同名称*/}:{rowInfo.contractAssociatedDTO.contractName}</span>
                <span style={{marginLeft:'10px'}}>{messages('loan-billing.key108')/*合同编号*/}:{rowInfo.contractAssociatedDTO.contractNumber}</span>
                <span style={{marginLeft:'10px'}}>{messages('loan-billing.key109')/*计划付款日期*/}:{moment(rowInfo.contractAssociatedDTO.dueDate).format('YYYY-MM-DD')}</span>
                <span style={{marginLeft:'10px'}}>{messages('loan-billing.key110')/*计划付款行行号*/}:{rowInfo.contractAssociatedDTO.lineNumber}</span>
              </Col>
            </Row>
          )
        }
        <Row>
          <Col span={2}>{messages('loan-billing.key99')/*付款日志*/}:</Col>
          <Col span={22}>
            {
              rowInfo.transactionDetailDTOList.map(item => {
                return <div>
                  <span>{messages('loan-billing.key100')/*付款金额*/}:{`${item.curreny}  ${this.filterMoney(item.amount,queryCurrencyPrecision(item.curreny),true)}`}</span>
                  <span style={{marginLeft:'10px'}}>{messages('common.currency.rate')/*汇率*/}:{item.exchangeRate}</span>
                  <span style={{marginLeft:'10px'}}>{messages('loan-billing.key86')/*汇率日期*/}:{moment(item.payDate).format('YYYY-MM-DD')}</span>
                </div>
              })
            }
          </Col>
        </Row>
      </div>
    ) : <Spin spinning={rowLoading} />
  };

  //展示借款行详细信息
  renderAllExpandedRow = (expanded,record) => {
    if(expanded){
      this.setState({rowLoading:true});
      borrowService.getLineInfo(record.id).then(res => {
        record._info = res.data;
        this.setState({rowLoading:false});
      }).catch(e => {
        message.error(e.response.data.message);
        this.setState({rowLoading:false});
      })
    }
  };

  //编辑借款行
  editRecord = (e,record) => {
    e.stopPropagation();
    e.preventDefault();
    const { info } = this.state
    if (info.formCode === 'JK007') {
      this.setState({
        extendMoneyMode: 'edit',
        viewId: record.id,
      }, () => {
        this.setState({ extendMoneyFrame: true })
      })
    } else if (info.formCode === 'JK006') {
      this.setState({
        turnPermanentMode: 'edit',
        viewId: record.id,
      }, () => {
        this.setState({ turnPermanentFrame: true })
      })
    } else {
      this.setState({
        recordInfo: record.id,
        title: messages('loan-billing.key37')/*编辑借款计划*/
      },() => {
        this.setState({addShow: true});
      })
    }
  };

  //删除借款行
  deleteRecord = (e,record) => {
    e.stopPropagation();
    e.preventDefault();
    borrowService.deleteLoanLine(record.id).then(() => {
      this.getInfo();
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  //详情信息折叠扩展
  toggle = () => {
    const {expand} = this.state;
    this.setState({expand: !expand});
  };

  //渲染还款记录
  renderRepayment = () => {
    const { info, repayColumns } = this.state;
    return (
      <div className="tab-container">
        <Table columns={repayColumns}
               bordered
               rowKey="id"
               size="middle"
               onRow={record => ({
                 onClick: () => this.handleRepaymentClick(record)
               })}
               dataSource={info.repaymentList}/>
      </div>
    )
  };

  //点击还款记录的行
  handleRepaymentClick = (record) => {
    if(record.type === '2' || record.type === '3'){
      this.context.router.push(this.state.expenseDetail.url.replace(':expenseReportOID', record.expenseReportOid).replace(':pageFrom','my'));
    }else{
      this.setState({
        refundFrame: true,
        refundParams:record.repaymentOid
      })
    }
  };

  //多行借款单编辑关闭
  handleCloseEdit = (value,type) => {
    if(type === 'edit'){
      this.setState({editShow:false});
    } else if (type === 'refund'){
      this.setState({refundFrame:false});
    } else if(type === 'viewLine'){
      this.setState({viewFrame:false});
    } else {
      this.setState({addShow:false,recordInfo:''});
    }
    if(typeof value === 'boolean' && value){
      this.getInfo();
    }
  };

  //跳转信用页面
  handleIntoHonest = (e) => {
    e.stopPropagation();
    this.setState({honestModalShow: true});
  };

  //是否展示挂起
  isShowHangUp = () => {
    const { info } = this.state;
    let showHangUp = false;
    let approverOID = getQueryUrlParam('approverOID');
    info.approvalChains && info.approvalChains.map(chain => {
      if (chain.approverOID === approverOID && chain.pending) {
        showHangUp = true;
      }
    });
    return showHangUp;
  };

  render(){
    const {
      info, status, subStatus, editShow, formInfo, addShow, title, recordInfo, isRepaying, loanTableData,
      refundFrame, refundParams, authorityWithRepay, honestModalShow, applicationOID, requestInfo, viewFrame,
      viewId, debtInfo, debtVisible, extendMoneyFrame, turnPermanentFrame, extendMoneyMode, turnPermanentMode } = this.state;
    const { approving } = this.props.location.query;
    let applicant = info.applicant || {};
    //将是否是管理员添加进去
    info.admin = this.state.adminApprove;
    return(
      <div className='loan-detail background-transparent'>
        <div className='tabs-info' style={{position: 'relative'}}>
          <Tabs type="card" onChange={this.onChangeTabs} defaultActiveKey={status}>
            <TabPane tab={messages('loan-billing.key38')/*借款单信息*/} key="loanInfo">{this.renderHeadInfo(applicant)}</TabPane>
            <TabPane tab={messages('loan-billing.key39')/*审批历史*/} key="approvals">
              <ApproveHistory approvalChains={info.approvalChains}
                              isShowReply={this.props.params.pageFrom === 'my' && info.status === 1003}
                              businessCode={info.businessCode}
                              approvalHistory={info.approvalHistorys}
                              applicantInfo={applicant}
                              type="load"/>
            </TabPane>
          </Tabs>
          {!!approving && (
            <ApproveTag entityOID={this.props.params.loanBillOID}/>
          )}
        </div>
        {status === 'loanInfo' && (
          <Tabs className="detail-tabs" activeKey={subStatus} onChange={this.handleSubTabsChange}>
            <TabPane tab={messages('loan-billing.key33')/*借款单详情*/} key="detail">{this.renderDetailInfo(applicant)}</TabPane>
            {isRepaying && authorityWithRepay && (
              <TabPane tab={messages('loan-billing.key40')/*还款记录*/} key="repayment">{this.renderRepayment()}</TabPane>
            )}
          </Tabs>
        )}
        {info.type === 2006 && info.status === 1001 && <SlideFrame show={editShow}
                                                                   content={editLoan}
                                                                   title={messages('loan-billing.key41')/*编辑借款单*/}
                                                                   key='editLoan'
                                                                   params={{info,editShow,formInfo,requestInfo}}
                                                                   onClose={value => this.handleCloseEdit(value,'edit')}
                                                                   afterClose={value => this.handleCloseEdit(value, 'edit')}/>}
        {info.type === 2006 && info.status === 1001 && <SlideFrame show={addShow}
                                                                   title={title}
                                                                   key='addLine'
                                                                   content={addLoan}
                                                                   params={{addShow,info,recordInfo,formInfo}}
                                                                   onClose={value => this.handleCloseEdit(value,'add')}
                                                                   afterClose={value => this.handleCloseEdit(value, 'add')}/>}
        {info.repaymentList && info.repaymentList.length > 0 && <SlideFrame show={refundFrame}
                                                                            title={messages('loan-billing.key89')/*还款详情*/}
                                                                            key='refund'
                                                                            content={refundContent}
                                                                            params={{
                                                                              refundFrame,
                                                                              refundParams,
                                                                              location:this.props.location
                                                                            }}
                                                                            onClose={value => this.handleCloseEdit(value, 'refund')}
                                                                            afterClose={value => this.handleCloseEdit(value, 'refund')}/>}
        <SlideFrame show={viewFrame}
                    title={messages('loan-billing.key118')/*查看借款计划*/}
                    key='viewLine'
                    content={viewLine}
                    params={{
                      viewFrame,
                      viewId,
                      info
                    }}
                    onClose={value => this.handleCloseEdit(value, 'viewLine')}
                    afterClose={value => this.handleCloseEdit(value, 'viewLine')}/>
        <SlideFrame
          show={extendMoneyFrame}
          title="延长还款"
          key='extendMoney'
          content={extendLoad}
          params={{
            extendMoneyFrame,
            mode: extendMoneyMode,
            viewId,
            businessCode: info.businessCode,
            onClose: () => {
              this.getInfo();
              this.setState({ extendMoneyFrame: false })
            }
          }}
          onClose={() => {
            this.getInfo();
            this.setState({ extendMoneyFrame: false })
          }}
          afterClose={() => this.setState({ extendMoneyFrame: false })}
        />
        <SlideFrame
          show={turnPermanentFrame}
          title="转永久"
          key='turnPermanent'
          content={turnPermanent}
          params={{
            turnPermanentFrame,
            mode: turnPermanentMode,
            viewId,
            businessCode: info.businessCode,
            onClose: () => {
              this.getInfo();
              this.setState({ turnPermanentFrame: false })
            }
          }}
          onClose={() => {
            this.getInfo();
            this.setState({ turnPermanentFrame: false })
          }}
          afterClose={() => this.setState({ turnPermanentFrame: false })}
        />
        <Modal title={messages('expense-parent-report.key110')/*信用查看*/}
               width={900}
               footer={<div><Button type={'primary'} onClick={() => this.setState({honestModalShow:false})}>{messages('expense-parent-report.key111')/*关闭*/}</Button></div>}
               onCancel={() => this.setState({honestModalShow:false})}
               className={'honest-view-modal'}
               visible={honestModalShow}>
          <HonestView applicant={applicant}/>
        </Modal>
        <DebtModal visible={debtVisible} info={debtInfo} loanInfo={info} close={() => {this.setState({debtVisible: false, debtInfo: {}})}}/>
        <BottomButton info={info} location={this.props.location} routeObj={this.props.params} requestInfo={requestInfo} applicationOID={applicationOID} formInfo={formInfo} loanTableData={loanTableData}/>
      </div>
    )
  }
}


LoanDetail.contextTypes = {
  router: React.PropTypes.object
};

export default LoanDetail;
